package com.takeshequ.friends;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.annotation.view.ViewInject;

import org.json.JSONObject;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.takeshequ.BasicActivity;
import com.takeshequ.Constants;
import com.takeshequ.R;
import com.takeshequ.homepage.HomePageActivity;
import com.takeshequ.main.MainFragmentActivity;
import com.utils.HttpClientUtils;
import com.utils.HttpClientUtils.HttpResponseHandler;

public class AddressBookContactsActivity extends BasicActivity {
	@ViewInject(id = R.id.add_friends_from_address_book_back, click = "back")
	private Button back;
	@ViewInject(id = R.id.add_friends_from_address_book_listview)
	private ListView listView;
	private List<Contact> contacts = new ArrayList<Contact>();
	private ItemAdapter adapter;
	private Map<Integer, View> viewMap = new HashMap<Integer, View>();

	class Contact {
		String name;
		String phone;
		int opertion;// 0:已添加,1:未添加,2:未注册

		public int getOpertion() {
			return opertion;
		}

		public void setOpertion(int opertion) {
			this.opertion = opertion;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getPhone() {
			return phone;
		}

		public void setPhone(String phone) {
			this.phone = phone;
		}

	}

	@Override
	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_friends_from_address_book);
	};

	@Override
	protected void onResume() {
		super.onResume();
		new GetContactTask().execute("");
	}

	class ItemAdapter extends BaseAdapter {

		private LayoutInflater inflater;

		private class ViewHolder {
			public TextView nameTextView;
			public ImageView addImg;
			public TextView operationTextView;
		}

		public ItemAdapter(LayoutInflater inflater) {
			this.inflater = inflater;
		}

		@Override
		public int getCount() {
			return contacts.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (contacts.size() > position) {
				View view = viewMap.get(position);
				Contact contact = contacts.get(position);
				final ViewHolder holder;
				if (view == null) {
					view = inflater.inflate(
							R.layout.add_friends_from_address_book_list_item,
							parent, false);
					holder = new ViewHolder();
					holder.nameTextView = (TextView) view
							.findViewById(R.id.add_friends_from_address_book_listitem_nickName);
					holder.addImg = (ImageView) view
							.findViewById(R.id.add_friends_from_address_book_add_img);
					holder.operationTextView = (TextView) view
							.findViewById(R.id.add_friends_from_address_book_listitem_operation);
					view.setTag(holder);
					viewMap.put(position, view);
				} else {
					holder = (ViewHolder) view.getTag();
				}

				holder.nameTextView.setText(contact.getName());
				if (contact.getOpertion() == -1) {
					holder.operationTextView.setText("已添加");
					holder.operationTextView.setTextColor(getResources()
							.getColor(R.color.grey_label));
					holder.addImg.setVisibility(View.GONE);
					view.setClickable(false);
				} else if (contact.getOpertion() == -2) {
					holder.operationTextView.setText("邀请");
				} else if(contact.getOpertion() == 0){
					holder.operationTextView.setText("");
					holder.operationTextView.setTextColor(getResources()
							.getColor(R.color.grey_label));
					holder.addImg.setVisibility(View.GONE);
					view.setClickable(false);
				}else{
					holder.operationTextView.setText("添加");
				}
				// holder.setText(talkHistory.getDate());

				return view;
			}
			return null;

		}
	}

	private class GetContactTask extends AsyncTask<String, String, String> {
		public String doInBackground(String... params) {
			fetchAllContacts();
			return "";
		}

		@Override
		protected void onPreExecute() {
			contacts.clear();
		}

		@Override
		public void onPostExecute(String Re) {
			StringBuffer sbf = new StringBuffer();
			for (int i = 0; i < contacts.size(); i++) {
				sbf.append(contacts.get(i).getPhone());
				if (i < contacts.size() - 1) {
					sbf.append(",");
				}
			}
			Map<String, String> params = new HashMap<String, String>();
			params.put("memberId", Constants.memberId);
			params.put("mobileNumbers", sbf.toString());
			HttpClientUtils.get("isMobileNumberSignup", params,
					new HttpResponseHandler() {

						@Override
						public void handler(String response) {
							try {
								System.out.println(response);
								JSONObject jsonObject = new JSONObject(response);
								System.out.println(jsonObject
										.getString("state").equals("1"));
								if (jsonObject.getString("state").equals("1")) {

									HashMap map = gson.fromJson(
											jsonObject.getString("resultmap"),
											HashMap.class);
									System.out.println(map.size() + "-----"
											+ contacts.size());
									for (Contact contact : contacts) {

										 contact.setOpertion(Integer.valueOf(String
										 .valueOf(map.get(contact
										 .getPhone()))));
										System.out.println(map.get(contact
												.getPhone()));
										if(map.get(contact
												.getPhone()).equals(Constants.memberId)){
											contact.setOpertion(0);
										}

									}
									adapter = new ItemAdapter(
											AddressBookContactsActivity.this
													.getLayoutInflater());

									listView.setAdapter(adapter);
									listView.setOnItemClickListener(new OnItemClickListener() {
										@Override
										public void onItemClick(
												AdapterView<?> arg0, View arg1,
												int position, long arg3) {
											Contact contact = contacts
													.get(position);
											System.out.println(contact
													.getOpertion()
													+ ","
													+ contact.getName());
											if (contact.getOpertion() > 0) {
												Map<String, String> params = new HashMap<String, String>();
												params.put("fromMemberId",
														Constants.memberId);
												params.put("toMemberId", String
														.valueOf(contact
																.getOpertion()));
												HttpClientUtils
														.post("addFriend",
																params,
																new HttpResponseHandler() {

																	@Override
																	public void handler(
																			String response) {
																		Toast toast = Toast
																				.makeText(
																						AddressBookContactsActivity.this,
																						"发送申请成功",
																						3000);
																		toast.setGravity(
																				Gravity.CENTER,
																				0,
																				0);
																		toast.show();
																		System.out
																				.println(response);

																	}
																});
											}
										}

									});
									// adapter.notifyDataSetChanged();

								} else {
									Toast.makeText(
											AddressBookContactsActivity.this,
											jsonObject.getString("desc"), 3000)
											.show();
								}
							} catch (Exception e) {

							}
						}
					});

		}

		@Override
		protected void onProgressUpdate(String... values) {
		}
	}

	public void fetchAllContacts() {
		String id, name, phoneNumber = null;
		ContentResolver contentResolver = this.getContentResolver();
		Cursor cursor = contentResolver.query(
				android.provider.ContactsContract.Contacts.CONTENT_URI, null,
				null, null, null);
		cursor.getCount();
		while (cursor.moveToNext()) {
			id = cursor
					.getString(cursor
							.getColumnIndex(android.provider.ContactsContract.Contacts._ID));
			name = cursor
					.getString(cursor
							.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME));
			Cursor phoneCursor = contentResolver
					.query(android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							android.provider.ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ "=" + id, null, null);
			while (phoneCursor.moveToNext()) {
				phoneNumber = phoneCursor
						.getString(phoneCursor
								.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER));
			}
			phoneCursor.close();
			Contact contact = new Contact();
			contact.setName(name);
			contact.setPhone(phoneNumber.replace(" ", ""));
			contacts.add(contact);

		}
		cursor.close();
	}

	public void back(View v) {
		overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
		startActivity(new Intent(AddressBookContactsActivity.this,
				MainFragmentActivity.class));
	}
}
